package com.imddysc.dwz.service.impl;

import com.imddysc.dwz.entity.Links;
import com.imddysc.dwz.repository.LinksRepository;
import com.imddysc.dwz.service.LinksService;
import com.imddysc.dwz.utils.DecimalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LinksServiceImpl implements LinksService {

    @Autowired
    private LinksRepository linksRepository;

    @Override
    public Links addLinks(String url) {
        Links links = new Links();
        links.setUrl(url);
        links.setKeyword("");
        links.setType("custom");
        links.setInsertAt(LocalDateTime.now());
        links.setUpdatedAt(LocalDateTime.now());

        Links newLinks = linksRepository.saveAndFlush(links);
        newLinks.setKeyword(DecimalUtils._10_to_62(newLinks.getId()));
        newLinks = linksRepository.saveAndFlush(newLinks);
        return newLinks;
    }

    @Override
    public Links updateLinks(String oldUrl, String newUrl) {
        Links links = linksRepository.findByUrl(oldUrl).orElse(null);

        links.setUrl(newUrl);
        links.setUpdatedAt(LocalDateTime.now());

        Links newLinks = linksRepository.saveAndFlush(links);
        return newLinks;
    }

    @Override
    public void deleteLinks(String url) {
        Links links = linksRepository.findByUrl(url).orElse(null);
        linksRepository.delete(links);
    }

    @Override
    public Links getById(Long id) {
        return linksRepository.findById(id).orElse(null);
    }

    @Override
    public Links findLinksByUrl(String url) {
        return linksRepository.findByUrl(url).orElse(null);
    }

    @Override
    public void deleteLinksById(Long id) {
        linksRepository.deleteById(id);
    }

	@Override
	public Page<Links> findAllByPageable(Integer currentPage, Integer pageSize) {
		Pageable pageable = PageRequest.of(currentPage, pageSize);
		Page<Links> pageLinks = linksRepository.findAll(pageable);
		return pageLinks;
	}

	@Override
	public Links getLinks(Long id) {
		return linksRepository.findById(id).orElse(null);
	}

	@Override
	public Links saveAndFlushLinks(Links links) {
		return linksRepository.saveAndFlush(links);
	}

}
